//
//  ApiService.swift
//  MyTouTiao
//
//  Created by Yuri on 2018/3/15.
//  Copyright © 2018年 Yuri. All rights reserved.
//

//使用Moya作为网络请求库（Moya是基于Alamofire库）

import Foundation
import Moya

enum ApiService {
    case category
    case categoryPost(id:Int)
    case submitComment(postId : Int, name : String, email : String, content : String)
}

//扩展ApiService实现Moya的TargetType协议
extension ApiService : TargetType {
    var baseURL: URL {
        let baseUrl = "http://localhost:8888/wordpress/api"
        return URL(string: baseUrl)!
    }
    
    var path: String {
        switch self {
        case .category:
            return "/get_category_index"
        case .categoryPost(_):
            return "/get_category_posts"
        case .submitComment(_,_,_,_):
            return "/respond/submit_comment"
        }
    }
    
    var method: Moya.Method {
        switch self {
        case .category, .categoryPost, .submitComment:
            return .get
        }
    }
    
    //单元测试
    var sampleData: Data {
        switch self {
        case .category:
            return "Category test data".utf8Encoded
        case .categoryPost(let id) :
            return "id=\(id)".utf8Encoded
        case .submitComment(let postId, let name, let email, let content):
            return "postId=\(postId),name=\(name),email=\(email),content:\(content)".utf8Encoded
        }
    }
    
    var task: Task {
        switch self {
        case .category:
            return .requestPlain
        case .categoryPost(let id):
            var params : [String : Any] = [:]
            params["id"] = id
            return .requestParameters(parameters: params, encoding: URLEncoding.default)
        case .submitComment(let postId, let name, let email, let content):
            var params : [String : Any] = [:]
            params["post_id"] = postId
            params["name"] = name
            params["email"] = email
            params["content"] = content
            return .requestParameters(parameters: params, encoding: URLEncoding.default)
        }
    }
    
    var headers: [String : String]? {
        return ["Content-type": "application/json"]
    }
    
}

// MARK: - Helpers
private extension String {
    var urlEscaped: String {
        return addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!
    }
    
    var utf8Encoded: Data {
        return data(using: .utf8)!
    }
}
